package com.ruix.app.manager;

import android.text.TextUtils;

import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.hyphenate.exceptions.HyphenateException;
import com.hyphenate.util.PathUtil;
import com.ruix.app.cache.CacheFactory;
import com.ruix.app.cache.cachetrans.UserCachetrans;
import com.ruix.app.constant.RuiXConstant;
import com.ruix.app.model.ChatAuther;
import com.ruix.app.model.Classes;
import com.ruix.app.model.Lesson;
import com.ruix.app.model.User;
import com.ruix.app.util.EMMessageUtil;
import com.ruix.app.util.LogUitl;
import com.ruix.app.util.MD5Util;

import java.util.HashMap;

/**
 * Created by hadexs on 2017/4/22.
 */

public class UserManager {
    private static UserManager userManager;
    private static User currentUser;
    private Classes currentClass;
    private Lesson currentLesson;
    private HashMap<String,ChatAuther> chatAuthers;
    private String currentClassID;//当前班级id
    private String currentLessonID;//当前课程id


    private UserManager() {
    }


    public synchronized void init() {
        if (currentUser == null) {
            String currentUid = ClientInfo.getCurrentUid();
            if (!TextUtils.isEmpty(currentUid)) {
                loadCurrentUser(currentUid);
            }
            chatAuthers = new HashMap<>();
        }
    }


    public static UserManager sharedInstance() {
        if (userManager == null) {
            synchronized (UserManager.class) {
                if (userManager == null) {
                    userManager = new UserManager();
                    userManager.init();
                }
            }
        }
        return userManager;
    }

    public static User getCurrentUser() {
        if (currentUser == null) {
            currentUser = new User();
        }
        return currentUser;
    }




    public synchronized void loadCurrentUser(String uid) {
        User user = CacheFactory.synchLoadCache(uid, new UserCachetrans());
        if (user != null) {
            currentUser = user;
        }
    }

    public void setCurrentUser(User user){
        if (user != null && !TextUtils.isEmpty(user.getID())) {
            currentUser = user;
            saveCurrentUser();
        }
    }

    public void updateUserInfo(User user){
        if (user != null && !TextUtils.isEmpty(user.getID())) {
            if (currentUser != null && user.getID().equals(currentUser.getID())) {
                currentUser.setID(user.getID());
                currentUser.setName(user.getName());
                currentUser.setMobie(user.getMobie());
                currentUser.setAvatar(user.getAvatar());
                currentUser.setPosition(user.getPosition());
                currentUser.setBirthday(user.getBirthday());
                currentUser.setGender(user.getGender());
                currentUser.setEmail(user.getEmail());
                currentUser.setCompany(user.getCompany());
                currentUser.setLocate(user.getLocate());
            } else {
                currentUser = user;
            }
            saveCurrentUser();
        }


    }

    public void saveCurrentUser(){
        ClientInfo.setCurrentUid(currentUser.getID());
        CacheFactory.cacheUser(currentUser);
    }

    public boolean hasLogin(){
        if (currentUser != null){
            return  true;
        }
        return false;
    }

    private String buildHuanXinPwd(String emmid){
        return MD5Util.getMD5String(RuiXConstant.EM_PWD_KEY+emmid).toUpperCase();
//        return MD5Util.getMD5String(emmid).toUpperCase();
    }


    public void loginEMClient(){
        if (currentUser != null && !TextUtils.isEmpty(currentUser.getID())) {
            String emmid = currentUser.getID();
            String emmPwd =buildHuanXinPwd(emmid);
            EMMessageUtil.login(emmid, emmPwd, new EMCallBack() {
                @Override
                public void onSuccess() {
                    EMClient.getInstance().groupManager().loadAllGroups();
                    EMClient.getInstance().chatManager().loadAllConversations();
                    currentUser.setLoginHX(true);
                }

                @Override
                public void onError(int i, String s) {
                    if (i==204){// 用户不存在
                        registHuanXin();
                    }
                    currentUser.setLoginHX(false);
                }

                @Override
                public void onProgress(int i, String s) {

                }
            });

        }
    }

    public void registHuanXin(){
        new Thread(){
            @Override
            public void run() {
                if (currentUser != null && !TextUtils.isEmpty(currentUser.getID())) {
                    String emmid = currentUser.getID();
                    String emmPwd =buildHuanXinPwd(emmid);
                    try {
                        EMMessageUtil.acreateAccount(emmid, emmPwd);
                    } catch (HyphenateException e) {
                        e.printStackTrace();
                    }
                    EMMessageUtil.login(emmid, emmPwd, new EMCallBack() {
                        @Override
                        public void onSuccess() {
                            EMClient.getInstance().groupManager().loadAllGroups();
                            EMClient.getInstance().chatManager().loadAllConversations();
                            currentUser.setLoginHX(true);
                        }

                        @Override
                        public void onError(int i, String s) {
                            currentUser.setLoginHX(false);
                        }

                        @Override
                        public void onProgress(int i, String s) {

                        }
                    });
                }
            }
        }.start();

    }

    public void logoutHuanXin(){
        EMClient.getInstance().logout(true, new EMCallBack() {

            @Override
            public void onSuccess() {
                currentUser.setLoginHX(false);
            }

            @Override
            public void onProgress(int progress, String status) {

            }

            @Override
            public void onError(int code, String message) {
            }
        });
    }

    public Classes getCurrentClass() {
        return currentClass;
    }

    public void setCurrentClass(Classes currentClass) {
        this.currentClass = currentClass;
        this.currentClassID = currentClass.getID();
    }

    public void updateCurrentClassState(Classes newClass){
        if (currentClass != null  && newClass != null && currentClass.getID().equals(newClass.getID())){
            currentClass.setName(newClass.getName());
            currentClass.setStatus(newClass.getStatus());
            currentClass.setType(newClass.getType());
            currentClass.setOrganization(newClass.getOrganization());
        }
    }


    public Lesson getCurrentLesson() {
        return currentLesson;
    }

    public void setCurrentLesson(Lesson currentLesson) {
        this.currentLesson = currentLesson;
        setCurrentLessonID(currentLesson.getId());
    }



    public void clearChatAuthers(){
        if (chatAuthers != null){
            chatAuthers.clear();
        }
    }

    public synchronized void addChatAuther(ChatAuther auther){
        if (chatAuthers == null){
            chatAuthers = new HashMap<>();
        }
        if (!chatAuthers.containsKey(auther.getAuthID())){
            chatAuthers.put(auther.getAuthID(),auther);
        }
    }

    public ChatAuther getChatAuther(String authid){
        if (authid != null && chatAuthers != null){
           return chatAuthers.get(authid);
        }
        return null;
    }

    public String getCurrentClassID() {
        return currentClassID;
    }

    public void setCurrentClassID(String currentClassID) {
        this.currentClassID = currentClassID;
    }

    public String getCurrentLessonID() {
        return currentLessonID;
    }

    public void setCurrentLessonID(String currentLessonID) {
        this.currentLessonID = currentLessonID;
    }
}
